package com.mfy.filter;

import com.mfy.entity.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;
@Component
public class CheckTokenGatewayFilterFactory extends AbstractGatewayFilterFactory<CheckTokenGatewayFilterFactory.Config> {
    public CheckTokenGatewayFilterFactory() {
        super(CheckTokenGatewayFilterFactory.Config.class);
    }
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public GatewayFilter apply(Config config) {
        return new GatewayFilter() {
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                ServerHttpRequest request = exchange.getRequest();
                if(config.requiredToken) {
                    //0.从request里面获取token信息
                    String token = request.getQueryParams().getFirst("token");
                    //1.判断配置文件中requiredToken是否为true
                    //2.如果为true，检查redis里面是否有该token信息。
                    if(StringUtils.isEmpty(token)){
                        throw new RuntimeException("没有令牌。。。");
                    }
                    //3.如果有token放行请求
                    Admin admin = (Admin)redisTemplate.opsForValue().get(token);
                    System.out.println("admin = " + admin);
                    if(ObjectUtils.isEmpty(admin)){
                        //4.如果没有拦截请求，报错
                        throw new RuntimeException("无效的token!!");
                    }
                }
                return chain.filter(exchange);
            }
        };
    }

    //把配置文件中的CheckToken的值赋值为Config类的requiredToken属性
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("requiredToken");
    }

    public static class Config {
        private boolean requiredToken;
        public Config() {
        }

        public boolean isRequiredToken() {
            return requiredToken;
        }

        public void setRequiredToken(boolean requiredToken) {
            this.requiredToken = requiredToken;
        }
    }
}

